<?php
namespace humhub\modules\api\controllers;

use Yii;
use humhub\modules\api\controllers\BaseController;
use humhub\modules\user\models\User;
use humhub\modules\space\models\Space;
use humhub\modules\space\models\Membership;
use humhub\modules\user\widgets\UserListBox;
use humhub\modules\post\models\Post;
use humhub\modules\content\models\Content;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 获取指定用户的Space列表, 基本信息、Posts、Tags、关注&成员列表、关注取消操作等...
 */
class ProfileController extends Base2Controller
{
    public $modelClass = 'humhub\modules\api\models\Profile';

    /**
     * @inheritdoc
     */
    public function init(){
        $_GET['uguid'] = Yii::$app->request->get('u');
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];
        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['delete'], $actions['update'], $actions['create']);
        return $actions;
    }

    /**
     * 用户标签
     *
     * GET /api/profile/tags?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array 标签列表 
     */
    function actionTags(){
        $user = $this->contentContainer;
        $tags = [];
        foreach($user->getTags() AS $tag){
            $tags[] = $tag;
        }
        return $tags;
    }

    /**
     * 关注用户
     *
     * POST /api/profile/follow?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return boolean
     */
    public function actionFollow(){
        $this->forcePostRequest();
        if( $this->getUser()->follow() ){
            return true;
        }
        Yii::$app->params['res-success'] = false;
        return false;
        /*
        // User cannot follow himself
        //if ($this->owner->className() == \humhub\modules\user\models\User::className() && $this->owner->getPrimaryKey() == $userId) { return false; }
        if( $myId == $userId ){
            return [];
        }
        $follow = $this->getFollowRecord($userId, $myId, 'humhub\modules\user\models\User');

        if ($follow === null) {
            $follow = new Follow();
            $follow->user_id = $userId;
            $follow->object_id = $myId;
            $follow->object_model = 'humhub\modules\user\models\User';
        }
        //通知
        $follow->send_notifications = 1;

        if( $follow->save() ){
            return true;
        }
        return false;
         */
    }

    /**
     * 取消关注用户
     *
     * POST /api/profile/unfollow?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return boolean
     */
    public function actionUnfollow(){
        $this->forcePostRequest();
        if( $this->getUser()->unfollow() ){
            return true;
        }
        Yii::$app->params['res-success'] = false;
        return false;
        /*
        if( $myId == $userId ){
            return [];
        }

        $record = $this->getFollowRecord($userId, $myId, 'humhub\modules\user\models\User');
        if ($record !== null) {
            if ($record->delete()) {
                return true;
            }
        } else {
            return false;
        }
        return false;
        private function getFollowRecord($userId, $myId, $obj_model){
            //humhub\modules\user\models\User
            //humhub\modules\post\models\Post
            return Follow::find()->where(['object_model' => $obj_model, 'object_id' => $myId, 'user_id' => $userId])->one();
        }
         */
    }

    /**
     * 获取用户的板块Space(包含加入的Space)列表
     *
     * GET /api/profile/space-membership-list?u=[guid]
     *
     * get.guid : 用户guid
     *
     * get.s_type : 新增筛选条件-类型筛选: 空=全部, 1=任务, 2=课程, 5=院校
     *
     * @return array guid:板块guid, bannerimage:Banner图, spacename:名称, description:描述
     */
    public function actionSpaceMembershipList(){
        $query = \humhub\modules\space\models\Membership::getUserSpaceQuery($this->getUser());

        if (!$this->getUser()->isCurrentUser()) {
            $query->andWhere(['!=', 'space.visibility', \humhub\modules\space\models\Space::VISIBILITY_NONE]);
        }

        $s_type  = (int) Yii::$app->request->get('s_type', 0);
        if( $s_type==1 || $s_type==2 || $s_type==5 ){
            $query->andWhere(['space.s_type' => $s_type]);
        }


        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $spaces = $query->offset($pagination->offset)->limit($pagination->limit)->all();
        //echo $query->createCommand()->getRawSql();exit;//sql
        //echo $query->createCommand()->sql;exit;//sql-safe

        $s = [];
        /*
        foreach($spaces AS $space){
            $sone['guid'] = $space->guid;
            $sone['bannerimage'] = $space->getProfileImage()->getUrl();
            $sone['spacename'] = $space->name;
            $sone['description'] = $space->description;
            $s[] = $sone;
        }
        return $s;
         */

        foreach($spaces as $space){
            //$d['follow'] = $this->getSpaceFollw($space);
            $d['ismember'] = 0;
            if ($space->isMember()) {
                $d['ismember'] = 1;
            }

            $d['img'] = $space->getProfileImage()->getUrl();

            $d['guid'] = $space->guid;

            $d['name'] = $space->name;
            $d['description'] = $space->description;

            $d['tags'] = [];
            if( $space->hasTags() ){
                $tag = array_chunk($space->getTags(), 5);
                $d['tags'] = $tag[0];
            }

            $d['s_type'] = $space->s_type;
            $d['s_v'] = $space->s_v; //+V
            //$d['s_img'] = $space->s_img;
            $d['s_img'] = '';
            $_file = \humhub\modules\file\models\File::findOne(['guid' => $space->s_img]);
            if( $_file ){
                if ($_file->getMimeBaseType() == "image"){
                    $d['s_img']  = $_file->getPreviewImageUrl(200, 200);
                }
            }
            $d['postcount'] = Content::find()->where([
                        'object_model' => Post::className(),
                        'contentcontainer_id' => $space->contentContainerRecord->id,
                    ])->count();

            $s[] = $d;
        }
        return array(
            'spaces' => $s,
        );
    }
    /**
     * 获取用户的板块Space列表(和space-membership-list不同的是，此列表仅包含此用户创建的)
     *
     * GET /api/profile/space-list?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array 参考space-membership-list
     */
    public function actionSpaceList(){
        $query = \humhub\modules\space\models\Membership::getUserSpaceQuery($this->getUser());

        if (!$this->getUser()->isCurrentUser()) {
            $query->andWhere(['!=', 'space.visibility', \humhub\modules\space\models\Space::VISIBILITY_NONE]);
        }
        //create_by = $this->getUser
        $query->andWhere(['space.created_by' => $this->getUser()->id]);

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $spaces = $query->offset($pagination->offset)->limit($pagination->limit)->all();

        $s = [];
        foreach($spaces AS $space){
            $sone['guid'] = $space->guid;
            $sone['bannerimage'] = $space->getProfileImage()->getUrl();
            $sone['spacename'] = $space->name;
            $sone['description'] = $space->description;
            $s[] = $sone;
        }
        return $s;
    }

    /**
     * 获取用户关注的列表
     *
     * GET /api/profile/followed-users-list?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array guid用户guid, profileimage:头像, displayname:姓名, title:个人Title, (follow说明:值=follow表示可以关注,=unfollow表示可以取消关注,=''无操作) 
     */
    public function actionFollowedUsersList(){
        $query = User::find();
        $query->leftJoin('user_follow', 'user.id=user_follow.object_id and object_model=:userClass and user_follow.user_id=:userId', [':userClass' => User::className(), ':userId' => $this->getUser()->id]);
        $query->orderBy(['user_follow.id' => SORT_DESC]);
        $query->andWhere(['IS NOT', 'user_follow.id', new \yii\db\Expression('NULL')]);
        $query->active();

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $u = [];
        foreach($users AS $user){
            $uone['guid']         = $user->guid;
            $uone['profileimage'] = $user->getProfileImage()->getUrl();
            $uone['displayname']  = $user->displayName;
            $uone['title']        = $user->profile->title;
            $uone['follow']       = \humhub\modules\api\models\Follow::getFollow($user, Yii::$app->user->id);//$this->getUser()->id
            $uone['countFollowers'] = $user->getFollowerCount(); //被关注
            $uone['u_v']          = $user->u_v;
            $u[] = $uone;
        }
        return $u;
    }

    /**
     * 获取用户被关注列表
     *
     * GET /api/profile/follower-list?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array guid用户guid, profileimage:头像, displayname:姓名, title:个人Title
     */
    public function actionFollowerList(){
        $query = User::find();
        $query->leftJoin('user_follow', 'user.id=user_follow.user_id and object_model=:userClass and user_follow.object_id=:userId', [':userClass' => User::className(), ':userId' => $this->getUser()->id]);
        $query->orderBy(['user_follow.id' => SORT_DESC]);
        $query->andWhere(['IS NOT', 'user_follow.id', new \yii\db\Expression('NULL')]);
        $query->active();

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $u = [];
        foreach($users AS $user){
            $uone['guid'] = $user->guid;
            $uone['profileimage']= $user->getProfileImage()->getUrl();
            $uone['displayname'] = $user->displayName;
            $uone['title']       = $user->profile->title;
            $uone['follow']      = \humhub\modules\api\models\Follow::getFollow($user, Yii::$app->user->id);//$this->getUser()->id
            $uone['countFollowers'] = $user->getFollowerCount(); //被关注
            $uone['u_v']          = $user->u_v;
            $u[] = $uone;
        }
        return $u;
    }

    /**
     * 获取用户互相关注列表
     *
     * GET /api/profile/friends?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array guid用户guid, profileimage:头像, displayname:姓名, title:个人Title
     */
    public function actionFriends(){
        $query = User::find();
        $query->leftJoin('user_follow', 'user.id=user_follow.user_id and object_model=:userClass and user_follow.object_id=:userId', [':userClass' => User::className(), ':userId' => $this->getUser()->id]);
        $query->orderBy(['user_follow.id' => SORT_DESC]);
        $query->andWhere(['IS NOT', 'user_follow.id', new \yii\db\Expression('NULL')]);
        $query->active();

        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $u = [];
        foreach($users AS $user){
            $uone['guid'] = $user->guid;
            $uone['profileimage']= $user->getProfileImage()->getUrl();
            $uone['displayname'] = $user->displayName;
            $uone['title']       = $user->profile->title;
            $uone['follow']      = \humhub\modules\api\models\Follow::getFollow($user, Yii::$app->user->id);//$this->getUser()->id
            $uone['countFollowers'] = $user->getFollowerCount(); //被关注
            $uone['u_v']          = $user->u_v;
            $u[] = $uone;
        }
        return $u;
    }

    /**
     * 关于该用户关注，板块数量, 头像等
     *
     * GET /api/profile/home?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array countfollowers:被关注数, countFollowing:关注数, countSpaces:板块Space数, profileimage:头像, bannerimage:Banner图, displayname:姓名, title:描述, (新增countOpus:作品数量(包含Space和Post))
     */
    public function actionHome(){
        $user = $this->contentContainer;

        $countFollowing = $user->getFollowingCount(User::className());
        $countUserSpaces = Membership::getUserSpaceQuery($user)
                ->andWhere(['!=', 'space.visibility', Space::VISIBILITY_NONE])
                ->andWhere(['space.created_by' => $user->id])  //仅限自己创建
                ->andWhere(['space.status' => Space::STATUS_ENABLED])
                ->count();
        $c_post = Content::find()->where([
                    'object_model' => Post::className(),
                    'created_by' => $user->id,
                    'contentcontainer_id' => $user->contentcontainer_id,
                ])->count();
        $countOpus = $countUserSpaces + $c_post;

        $countTask = Membership::getUserSpaceQuery($user)
                ->andWhere(['!=', 'space.visibility', Space::VISIBILITY_NONE])
                ->andWhere(['space.created_by' => $user->id])  //仅限自己创建
                ->andWhere(['space.s_type' => 1])
                ->andWhere(['space.status' => Space::STATUS_ENABLED])
                ->count();
        $countCourse = Membership::getUserSpaceQuery($user)
                ->andWhere(['!=', 'space.visibility', Space::VISIBILITY_NONE])
                ->andWhere(['space.created_by' => $user->id])  //仅限自己创建
                ->andWhere(['space.s_type' => 2])
                ->andWhere(['space.status' => Space::STATUS_ENABLED])
                ->count();
        if( $user->id == Yii::$app->user->id ){
            $mphone = preg_replace('/(\d{3})(\d{4})(\d{4})/i', '$1****$3', $user->mphone);
        }else{
            $mphone = '';
        }

        return array(
            'displayname' => $user->displayname,
            'title'       => $user->profile->title,
            'countFollowers' => $user->getFollowerCount(), //被关注
            'countFollowing' => $countFollowing,
            'countSpaces'    => $countUserSpaces,          //板块
            'countOpus'      => $countOpus,                //作品
            'profileimage'   => $user->getProfileImage()->getUrl(),
            'bannerimage'    => $user->getProfileBannerImage()->getUrl(),
            'u_v'            => $user->u_v,
            'follow'         => \humhub\modules\api\models\Follow::getFollow($user),
            'countTask'      => $countTask,
            'countCourse'    => $countCourse,
            'mphone'         => $mphone,
            'guid'           => $user->guid,
        );
    }

    /**
     * 关于该用户基本信息(General)
     *
     * GET /api/profile/about?u=[guid]
     *
     * get.guid : 用户guid
     *
     * @return array 返回四组信息(General, Communication, Socialbookmarks, Custom）和网站上资料设置对应, 包含:Firestname, Lastname, Title, Street, Zip, City, Country..., 其中Custom是自定义属性,包含:u_v是否+V=1/0
     */
    public function actionAbout(){
        if (!$this->contentContainer->permissionManager->can(new \humhub\modules\user\permissions\ViewAboutPage())) {
            throw new \yii\web\HttpException(403, 'Forbidden');
        }

        $x = [];
        $user = $this->contentContainer;
        foreach($user->profile->getProfileFieldCategories() as $category){
            $t1 = strtr($category->title, array(' '=>''));
            foreach ($user->profile->getProfileFields($category) as $field){
                //$tit = strtr($field->title, array(' '=>''));
                //$x[$t1][$tit] = $field->getUserValue($user, false);
                $tit = strtr($field->internal_name, array(' '=>''));
                $x['profile'][$tit] = $field->getUserValue($user, false);
            }
        }
        $x['profile']['u_v'] = $user->u_v;
        return $x;
    }
}
